package com.hyy.springbootblog;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class JwtUtil {

    //签名信息
    public static String secret = "oeWWf6KofPvMtRj+RGiOBB59L6A4yG/TwOrVRkGUZZw=";
    public static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));


    //1.生成token
    @Test
    public void getToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("name", "zhangsan");
        map.put("age", 18);
        String token = Jwts.builder()
                .setClaims(map)
                .signWith(key)
                .compact();
        System.out.println(token);
    }


    // 校验token
    @Test
    void parseToken() {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6MSwiYWdlIjoxOH0.m0Y-O5Q2q-yWJ1rs4T8B2mraJNWcYqJodc1iy8OeCuc";

        try {
            //jwt解析器
            JwtParser build=Jwts.parserBuilder()
                    .setSigningKey(key)
                            .build();

            //申明：实际记录的内容
            Claims claims = build.parseClaimsJws(token).getBody();

            // 打印解析出的 Claims
            System.out.println("ID: " + claims.get("id"));
            System.out.println("Name: " + claims.get("name"));
            System.out.println("Age: " + claims.get("age"));

        } catch (Exception e) {
            // 如果验证失败或解析错误，打印错误信息
            System.out.println("Token is invalid or expired: " + e.getMessage());
        }
    }


    //3.生成key
    @Test
    public void getKey() {
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String enCode = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(enCode);
    }
}
